from django.conf import settings
from django.forms.models import model_to_dict
from django.db.models import Avg, Sum, Count, Max, Min, Q, F
from django.db import transaction
from django_filters import *
from django_filters.rest_framework import DjangoFilterBackend, FilterSet

from rest_framework import viewsets
from rest_framework import serializers
from rest_framework import versioning
from rest_framework.response import Response
from rest_framework.serializers import *
from rest_framework.validators import UniqueValidator, UniqueTogetherValidator  # 验证器
from rest_framework.filters import SearchFilter, OrderingFilter

from iClouds.apidev import filter_views
from iClouds.Permissions import (
    OR,
    AllPermissions,
    MyPermissions,
    BoxPermissions,
    WeChatPermissions,
    BarPermissions,
    XboxPermissions,
)
from iClouds.Authentication import (
    MyJWTAuthentication,
    BoxJWTAuthentication,
    WeChatJWTAuthentication,
    BarJWTAuthentication,
    XboxJWTAuthentication,
)

from mysqldb.models import *
from mysqldb.serializers import ListDjangoFilterBackend


class NoneSerializer(serializers.Serializer):
    """无序列化"""

    class Meta:
        fields = "__all__"


class AllinpayMemberListSerializer(serializers.ModelSerializer):
    """场所会员"""

    id = IntegerField(read_only=True)
    name = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="姓名",
    )
    idcode = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="身份证号码",
    )
    phone = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="联系电话",
    )
    openid = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="openid",
    )
    unid = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="unid",
    )
    email = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="电子邮箱",
    )
    avatar = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="会员头像",
    )
    hash = CharField(allow_blank=True, allow_null=True, max_length=255, help_text="校验码")
    creattime = DateTimeField(allow_null=True, required=False)
    lasttime = DateTimeField(allow_null=True, required=False)
    pid = IntegerField(allow_null=True, help_text="场所ID")
    localid = IntegerField(read_only=True, help_text="本地会员ID")

    # inter = SerializerMethodField()
    # money = SerializerMethodField()

    class Meta:
        model = AllinpayMemberList
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayMemberList.objects.all(), fields=("pid", "hash")
            )
        ]

    # def get_inter(self, attr):
    #     try:
    #         sess = AllinpayInterList.objects.get(id=attr.id)
    #     except BaseException as err:
    #         return None
    #     return model_to_dict(sess)

    # def get_money(self, attr):
    #     try:
    #         sess = AllinpayMoneyList.objects.get(id=attr.id)
    #     except BaseException as err:
    #         return None
    #     return model_to_dict(sess)


class AllinpayMemberConfSerializer(serializers.ModelSerializer):
    """会员设置"""

    id = IntegerField(label="ID", read_only=True)
    name = CharField(allow_blank=True, allow_null=True, help_text="配置项目")
    pid = IntegerField(allow_null=True, help_text="场所ID")
    status = IntegerField(allow_null=True, help_text="状态")
    remarks = CharField(allow_blank=True, allow_null=True, help_text="备注")

    class Meta:
        model = AllinpayMemberConf
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(
                queryset=AllinpayMemberConf.objects.all(), fields=("name", "pid")
            )
        ]


class AllinpayMemberinterListSerializer(serializers.ModelSerializer):
    """会员积分"""

    id = IntegerField(
        help_text="会员云ID",
        validators=[UniqueValidator(queryset=AllinpayMemberinterList.objects.all())],
    )
    integral = IntegerField(allow_null=True, help_text="积分")
    hash = CharField(allow_blank=True, allow_null=True, help_text="校验码")
    lasttime = DateTimeField(allow_null=True, help_text="最近时间")

    class Meta:
        model = AllinpayMemberinterList
        fields = "__all__"


class AllinpayMemberinterLogsSerializer(serializers.ModelSerializer):
    """会员积分日志"""

    id = IntegerField(read_only=True)
    mid = IntegerField(allow_null=True, help_text="会员本地ID")
    inter = IntegerField(allow_null=True, help_text="变更积分")
    currenint = IntegerField(allow_null=True, help_text="当前积分")
    reqsn = CharField(
        allow_blank=True, allow_null=True, required=False, help_text="账单号"
    )
    currenttime = DateTimeField(allow_null=True, help_text="当前时间")
    remarks = CharField(
        allow_blank=True, allow_null=True, required=False, help_text="备注"
    )
    localid = IntegerField(allow_null=True, help_text="本地记录ID")
    pid = IntegerField(allow_null=True, help_text="场所ID")

    class Meta:
        model = AllinpayMemberinterLogs
        fields = "__all__"


class AllinpayMembermoneyListSerializer(serializers.ModelSerializer):
    """会员钱包"""

    id = IntegerField(
        help_text="会员云ID",
        validators=[UniqueValidator(queryset=AllinpayMemberinterList.objects.all())],
    )
    integral = IntegerField(allow_null=True, help_text="积分")
    hash = CharField(allow_blank=True, allow_null=True, help_text="校验码")
    lasttime = DateTimeField(allow_null=True, help_text="最近时间")

    class Meta:
        model = AllinpayMembermoneyList
        fields = "__all__"


class AllinpayMembermoneyLogsSerializer(serializers.ModelSerializer):
    """会员钱包日志"""

    id = IntegerField(read_only=True)
    mid = IntegerField(allow_null=True, help_text="会员本地ID")
    inter = IntegerField(allow_null=True, help_text="变更积分")
    currenint = IntegerField(allow_null=True, help_text="当前积分")
    reqsn = CharField(
        allow_blank=True, allow_null=True, required=False, help_text="账单号"
    )
    currenttime = DateTimeField(allow_null=True, help_text="当前时间")
    remarks = CharField(
        allow_blank=True, allow_null=True, required=False, help_text="备注"
    )
    localid = IntegerField(allow_null=True, help_text="本地记录ID")
    pid = IntegerField(allow_null=True, help_text="场所ID")

    class Meta:
        model = AllinpayMembermoneyLogs
        fields = "__all__"


# =========================================================================================
class JSONSerializerField(serializers.Field):
    """Serializer for JSONField -- required to make field writable"""

    def to_internal_value(self, data):
        return data

    def to_representation(self, value):
        return value


class BMemberListSerializer(serializers.ModelSerializer):
    """凡商会员列表"""

    id = IntegerField(label="ID", read_only=True)
    name = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="真实姓名",
    )
    idcode = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="身份证号",
    )
    phone = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="手机号码",
    )
    nicename = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="昵称",
    )
    avatar = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="头像",
    )
    email = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="电子邮箱",
    )
    openid = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="微信OpenID",
    )
    unid = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="微信UnID",
    )
    hash = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="校验码",
        validators=[UniqueValidator(queryset=BMemberList.objects.all())],
    )
    gender = IntegerField(
        allow_null=True,
        max_value=2147483647,
        min_value=-2147483648,
        required=False,
        help_text="性别",
    )
    creatime = DateTimeField(read_only=True)

    class Meta:
        model = BMemberList
        fields = "__all__"


class BMemberLoginSerializer(serializers.Serializer):
    """会员登录"""

    pid = IntegerField(help_text="场所ID")
    pcname = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="计算机名",
    )
    # data = JSONSerializerField(help_text="会员信息")
    data = BMemberListSerializer(help_text="会员信息")

    class Meta:
        fields = "__all__"


# =====================================================
# =====================================================
# =============凡商会员系统分析=============================
# =====================================================
# =====================================================
class MemberLevelruleListSerializer(serializers.ModelSerializer):
    """会员等级规则"""

    id = IntegerField(label="ID", read_only=True)
    pid = IntegerField(allow_null=True, help_text="场所ID")
    status = IntegerField(max_value=1, min_value=0, default=0, help_text="默认等级")
    lastreg = IntegerField(
        allow_null=True,
        max_value=2147483647,
        min_value=-2147483648,
        required=False,
        help_text="注册天数 小于",
    )
    week = IntegerField(
        allow_null=True,
        max_value=2147483647,
        min_value=-2147483648,
        required=False,
        help_text="到店次数/周 大于",
    )
    lol = IntegerField(
        allow_null=True,
        max_value=2147483647,
        min_value=-2147483648,
        required=False,
        help_text="lol游戏指数 大于",
    )
    csgo = IntegerField(
        allow_null=True,
        max_value=2147483647,
        min_value=-2147483648,
        required=False,
        help_text="csgo游戏指数 大于",
    )
    steam = IntegerField(
        allow_null=True,
        max_value=2147483647,
        min_value=-2147483648,
        required=False,
        help_text="steam游戏指数 大于",
    )
    other = IntegerField(
        allow_null=True,
        max_value=2147483647,
        min_value=-2147483648,
        required=False,
        help_text="综合排名 小于",
    )
    onpay = IntegerField(
        allow_null=True,
        max_value=2147483647,
        min_value=-2147483648,
        required=False,
        help_text="上次消费间隔(天) 大于",
    )
    master = IntegerField(
        allow_null=True,
        max_value=2147483647,
        min_value=-2147483648,
        required=False,
        help_text="创建人",
        read_only=True,
    )
    curtime = DateTimeField(
        read_only=True, allow_null=True, required=False, help_text="创建时间"
    )
    name = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        validators=[UniqueValidator(queryset=MemberLevelruleList.objects.all())],
        help_text="等级名称",
    )
    bem = CharField(
        allow_blank=True,
        allow_null=True,
        max_length=255,
        required=False,
        help_text="备注",
    )

    class Meta:
        model = MemberLevelruleList
        fields = "__all__"

    def validate_pid(self, attr):
        try:
            AllinpayPlaceList.objects.get(id=attr)
        except BaseException as err:
            raise serializers.ValidationError("场所对象不存在")
        return attr


# print(repr(MemberLevelruleListSerializer()))
